<template>
  <!------------------------------------ 地址编辑页面 ------------------------------------
    @desc 地址编辑
    @author kyle
    @date 2021-03-05
    @props
      addressData   ———— 地址数据
      adressIndex   ———— 地址数据在列表中的排序
    @method
      closeEdit      ———— 关闭地址编辑页面
      useAddress     ———— 保存使用地址
      deleteAddress  ———— 删除地址
  -->
  <div>
    <van-nav-bar
      fixed
      :title="title"
      left-arrow
      @click-left="closeEdit"
    />
    <div class="has-top has-bottom bg-gray" style="min-height:100vh">
      <van-form ref="subForm">
        <van-cell-group class="mt-20 mlr-24 br-12 ofh">
          <van-field v-model="pageData.ContactName" type="text" label="联系人" placeholder="请填写姓名" :rules="[{ required: true, message: ' ' }]" />
          <van-field v-model="pageData.ContactTel" type="number" label="联系电话" placeholder="请填写正确的联系电话" :rules="[{ required: true, pattern: /^1[3456789]\d{9}$/, message: '' }]" />
          <van-field
            readonly
            clickable
            right-icon="arrow"
            name="area"
            :value="regionName"
            label="地址"
            placeholder="点击选择省市区"
            :rules="[{ required: true, message: ' ' }]"
            @click="getamap"
          />
          <van-field v-model="pageData.ContactAddress"   type="textarea" placeholder="请点击图标选择地址" :rules="[{ required: true, message: ' ' }] " >
            <template #right-icon>
              <svg-icon icon-class="location" class="fs-40" @goPage="getamap" />
            </template>
          </van-field>
          <!--<div v-show="isNew" class="pos-r">
            <van-field v-model="totalAddress" type="textarea" class="text-area fs-24" placeholder="黏贴地址信息，自动拆分姓名，电话和地址，最多支持100个汉字(如：张某某18000000000福建省xxxxx)" />
            <span class="pos-a idenBtn" @click="identify">识别</span>
          </div>-->
        </van-cell-group>
        <van-cell-group class="mt-20 mlr-24 br-12 ofh">
          <van-field readonly label="设为默认地址" center class="default-box">
            <template #button>
              <van-switch v-model="pageData.IsDefault" size="22" />
            <!-- <input v-model="pageData.IsDefault" type="checkbox" class="ads-checkbox"> -->
            </template>
          </van-field>
        </van-cell-group>
      </van-form>

      <div class="mlr-40">
        <button class="btn-large bg-primary color-white mt-40" @click="saveAddress">保存并使用</button>
        <button v-show="!isNew" class="btn-large bg-white color-dark mt-40" @click="deleteAddress(pageData.ID)">删除收货地址</button>
      </div>

    </div>
    <van-popup v-model="showArea" position="bottom">
      <areaSelect :address-data="pageData" @pickArea="pickArea" />
    </van-popup>
		<!-- 地图弹出层 -->
		<van-popup v-model="AmapShow" position="bottom" class="bottom-popup">
      <AmapSearch v-if="showAmap"  class=" bg-gray" style="min-height:100vh" @closeAmap="closeAmap" @changeMap="changeMap" :timeNow="new Date()" :Lng="Lng" :Lat="Lat" :amapaddress="amapaddress" :city="city"/>
    </van-popup>
  </div>
</template>

<script>
import areaSelect from 'components/address/areaSelect'
import areaList from 'utils/area'
import { UserAddressAddOrEdit, BatchSmartParse, UserAddressDelete } from 'api/member'
import AmapSearch from 'components/address/amapSearch'
import { GetStorePage,  GetCityIdByCode, GetUserCityId } from 'api/store'
export default {
  name: 'AddressEdit',
  components: {
    areaSelect,
		AmapSearch,
  },
  props: {
    addressData: { // 地址数据
      type: Object,
      required: false,
      default: function() {
        return {}
      }
    },
    adressIndex: {
      type: Number,
      required: false,
      default: -1
    },
		addressId: {
			type: Number,
			default: 0,
		},
    userId: {
			type: Number,
			default: 0,
		}

  },
  data() {
    return {
      title: '',
      isNew: false,
      showArea: false,
      areaList: {},
      pageData: {
				ContactName: '',
				ContactTel: '',
			},
      regionName: '',
      totalAddress: '',
			Lng:0, //经度
			Lat:0 , // 维度
			AmapShow:false,
			amapaddress:'',
			city:'' , //城市
			locationCity: {
        ID: 0,
        Name: '定位中...'
      },
      // 初始化定位flag
      locationInit: false,
			showAmap: false
    }
  },
  watch: {
    addressData(newVal, oldVal) {
      this.initData(newVal)
    },
  },
	
	created(){	
		//this.getPosition()
	},
  mounted() {
    this.areaList = areaList
    this.initData(this.addressData)
  },
  methods: {
		getamap(){
			this.AmapShow = true
			this.showAmap = true
		},
		closeAmap(){
			this.AmapShow = false
			this.showAmap = false
		},
		changeMap(address){
			console.log("位置信息",address)
			let item = JSON.parse(address)
			console.log('mapaddress',item)
			this.pageData.ContactAddress = item.address
			this.Lng = item.lng
			this.Lat = item.lat

			const _data = {
        //ContactAddress: this.pageData.ContactName+this.pageData.ContactTel+item.address+',',
				ContactAddress: item.address+',',
      }
			console.log('复制后的_data',_data)	
      const _arr = []
      _arr.push(_data)
      const _obj = {
        list: _arr
      }
      this.BatchSmartParse(_obj)
		},
    initData(data) {
      // copy数据，保留原来的数据，修改再新数据中完成
      this.pageData = JSON.parse(JSON.stringify(data))
      if (JSON.stringify(this.pageData) === '{}') {
        this.title = '新增地址'
        this.isNew = true
				this.regionName = ''
      } else {
        this.title = '编辑地址'
        this.regionName = (this.pageData.ProvinceName || '') + (this.pageData.CityName || '') + (this.pageData.AreaName || '') + (this.pageData.StreetName || '')
        this.isNew = false
				this.city = this.pageData.CityName
      }
    },
    // 关闭编辑弹窗
    closeEdit() {
      this.$emit('closeEdit')
    },
    // 确认选择省市区
    pickArea(areaObj) {
      console.log(areaObj)
      this.pageData.ProvinceName = areaObj.ProvinceName
      this.pageData.ProvinceId = areaObj.ProvinceId
      this.pageData.CityName = areaObj.CityName
			this.city = areaObj.CityName
      this.pageData.CityId = areaObj.CityId
      this.pageData.AreaName = areaObj.AreaName
      this.pageData.AreaId = areaObj.AreaId
      this.pageData.StreetName = areaObj.StreetName
      this.pageData.StreetId = areaObj.StreetId
      this.regionName = (this.pageData.ProvinceName || '') + (this.pageData.CityName || '') + (this.pageData.AreaName || '') + (this.pageData.StreetName || '')
      this.showArea = false
    },   
  
    // 识别接口
    identify() {
			console.log('开始识别')
      let addressStr = this.totalAddress
      addressStr = addressStr.replace(/；/g, ';') // 去掉空格
      if (/1\d{9}.*\n.*1\d{9}/.test(addressStr)) {
        addressStr = addressStr.replace(/\n/g, ';')
      }
      addressStr = addressStr.replace(/\s/g, '')
      if (addressStr.charAt(addressStr.length - 1) === ';') {
        addressStr = addressStr.substring(0, addressStr.length - 1)
      }
      const targetAds = addressStr.split(';')[0]
      // var backinfo = this.$utils.AutoDistinguishAddress(targetAds)
      var tag_address = {
        //ContactName: backinfo.name.replace(/[,|，|；|;|\s]/g, ''),
        ContactAddress: targetAds.replace(/[,|，|；|;|\s]/g, ''),
        //ContactTel: backinfo.phone.replace(/[,|，|；|;|\s]/g, '')
      }
      console.log('tag_address',tag_address)
      const _arr = []
      _arr.push(tag_address)
      const _obj = {
        list: _arr
      }
      this.BatchSmartParse(_obj)
    },

    // 保存修改
    saveAddress() {
      this.$refs.subForm.validate().then(() => {
        console.log('通过验证',this.pageData)
				this.pageData.ID = this.addressId
        this.UserAddressAddOrEdit(this.pageData)
      })
    },
    // 删除地址
    deleteAddress(id) {
      this.$dialog.confirm({
        message: '确定要删除该地址？'
      })
        .then(() => {
          // 调用删除地址接口
          this.UserAddressDelete(id)
        })
        .catch(() => {
          // on cancel
        })
    },

    // 新增、编辑地址
    UserAddressAddOrEdit(obj) {
			obj.Lng = this.Lng
			obj.Lat = this.Lat
      if(this.userId){
        obj.userId = this.userId
      }
      UserAddressAddOrEdit(obj).then(res => {
        if (res) {
          console.log(res)
          const _obj = obj
          _obj.ID = res.Data
          this.$emit('useAddress', _obj, this.adressIndex)
        }
      })
    },
    UserAddressDelete(ids) {
      UserAddressDelete({ ids }).then(res => {
        if (res) {
          console.log('shanchu ')
          this.$toast.success('删除成功')
          console.log('删除')
          this.$emit('deleteAddress', this.adressIndex)
        }
      })
    },
    // 识别地址
    BatchSmartParse(data) {
			console.log('识别前导入的data',data)
      BatchSmartParse(data).then(res => {
        if (res) {
					this.regionName = ''
					const pageData =  res.Data.list[0]
					this.pageData.ProvinceName = pageData.ProvinceName
					this.pageData.CityName = pageData.CityName
					this.pageData.AreaName = pageData.AreaName
					this.pageData.StreetName = pageData.StreetName
          this.pageData.ContactAddress = pageData.ContactAddress
					this.pageData.ProvinceId = pageData.ProvinceId
					this.pageData.CityId = pageData.CityId
					this.pageData.AreaId = pageData.AreaId
					this.pageData.StreetId = pageData.StreetId
					console.log('识别接口后的res',res)
          this.regionName = (pageData.ProvinceName || '') + (pageData.CityName || '') + (pageData.AreaName || '') + (pageData.StreetName || '')
        }
      })
    },

		getPosition() {
      // 获取当前城市（缓存）
      const _str = localStorage.getItem('SelectCity')
			console.log(_str)
      if (_str) {
        const _obj = JSON.parse(_str)
        this.locationCity.Name = _obj.Name
        this.locationCity.ID = _obj.ID
        // 获取经纬度缓存
        const _GeolocationData = localStorage.getItem('GeolocationData')
        if (_GeolocationData) { // 存在定位缓存
				} else {
          // 调用定位获取经纬度
          this.getCurrentPosition(_obj.Name)
        }
			} else {
        this.GetUserCityId()
      }
		},
		// 监听定位
    getCurrentPosition(cityName) {
      const _this = this
      // 对查询条件经纬度赋值0 0
    

      _this.locationCity.Name = cityName || '定位中...'
      _this.locationInit = !!cityName
      console.log(_this.locationInit)
      this.$toast.loading({
        forbidClick: true,
        message: 'loading...',
        loadingType: 'spinner',
        duration: 0
      })
      _this.$geolocation.getCurrentPosition(function(status, result) {
        if (status === 'complete') {
          _this.onComplete(result)
        } else {
          _this.onError(result)
        }
      })
    },

    // 精准定位成功
    onComplete(data) {
      console.log('精准定位成功')
      console.log(data,"选择地区")
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      //this.closeAreaSelect(false)
     
      if (!this.locationInit) {
        this.locationCity.Name = data.addressComponent.district || data.addressComponent.city
        const adcode = parseInt(data.addressComponent.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // 精准定位失败
    onError(data) {
      console.log('精准定位失败')
      const _this = this
      _this.$geolocation.getCityInfo(function(status, result) {
        if (status === 'complete') {
          _this.onComplete1(result)
        } else {
          _this.onError1(result)
        }
      })
    },
    // ip定位成功
    onComplete1(data) {
      console.log('ip定位成功')
      console.log(data,"地区")
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      //this.closeAreaSelect(false)
      // 第一次初始化定位城市
      if (!this.locationInit) {
        this.locationCity.Name = data.city
        const adcode = parseInt(data.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // ip定位失败
    onError1(data) {
      console.log('ip定位失败')
      console.log(data)
      this.$toast.clear()
      this.$toast.fail({
        message: '获取定位信息失败，请刷新',
        icon: 'close'
      })
      this.locationCity.Name = '未知'
      setTimeout(() => {
        if (!this.locationInit) {
          this.locationInit = true
          this.listLoad = true
          this.isRefresh = true
          this.onRefresh()
        }
      }, 1000)
    },
		 // 获取城市id
		 GetCityIdByCode(code) {
      GetCityIdByCode({ RegionCode: code }).then(res => {
        if (res) {
          this.locationCity.ID = res.Data

          const _str = JSON.stringify(this.locationCity)
          localStorage.setItem('SelectCity', _str)
        }
      })
    },
    // 获取所属区域
    GetUserCityId() {
      GetUserCityId().then(res => {
        if (res && res.Data) {
          if (res.Data.ID === 0) {
            this.getCurrentPosition()
          } else {
            const _str = JSON.stringify(res.Data)
            localStorage.setItem('SelectCity', _str)
            this.getPosition()
          }
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.text-area{
 /deep/textarea{
   background:#f4f4f4;
   padding: 10px;
 }
}
.idenBtn{
  display: inline-block;
  line-height: 40px;
  padding: 0 18px;
  background: $color3;
  color:$colorF;
  border-radius: 8px;
  bottom: 30px;
  right: 50px;
}
.default-box{
  /deep/.van-field__button{
    display: flex;
    justify-items: center;
  }
  .van-switch--on{
    @include bg-primary
  }
}
.van-popup{
  background: transparent;
}
.mapPage{
width: 100%;
height: 100%;
z-index: $zIndexOverlay;
}
</style>

